<?php

namespace App\Http\Controllers;

use App\Models\Cartlist;
use App\Models\Wishlist;
use Illuminate\Http\Request;

class CartController extends Controller
{
    public function cartpage(){
        return view('cartpage');
    }

    public function addCart(Request $request){
        //获取当前用户名称
        $username = $request->cookie('usernameCookie');

        $pid = $request->input('pid');

        if($pid){
            //存储数据
            Cartlist::firstOrCreate(
                ['username'=>$username,'pid'=>$pid]
            );
        }else{
            return response()->json(array('status'=>1,'msg'=>'pid为空'));
        }

        return response()->json(array('status'=>0,'msg'=>'添加成功！'));
    }

    public static function getCart(){
        $cartInfos = array();
        $username = \request()->cookie('usernameCookie');

        $carts = Cartlist::where('username','=',$username)->get();

        foreach ($carts as $cart){
            //使用关联关系查询，一对多的关联关系
            $cartInfo = Cartlist::find($cart->id)->cartInfo;
            foreach ($cartInfo as $item){
                array_push($cartInfos,$item);
            }
        }
        return $cartInfos;
    }
}
